package kitwee.com.kanpad.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;


import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.jianghu.protocol.hadesheng.OutputCollection;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Timer;

import kitwee.com.kanpad.MyMultiDexApplication;

/**
 * Created by sven on 2017/6/22.
 */

public class PushService extends Service {
    private final IBinder mBinder = new PushBinder();
    private Socket socketClient;


    @Override
    public void onCreate() {
        super.onCreate();
    }

    private int PORT = 20480;//监听的端口号
    private String HOST = "192.168.3.39";
    //    private String HOST = "192.168.137.1";
    private int TIMEOUT = 2000;//socketserver 超时时间
    private DataOutputStream out = null;
    private DataInputStream input = null;
    //是否重连
    private boolean isReConnect = true;
    private Map<String, Map<String, String>> finalMap = new LinkedHashMap<>();

    public void init(final String ip, final int port) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    socketClient = createSocket();

                    while (true) {
                        if (socketClient != null && socketClient.isConnected()) {
                            LogUtils.e("服务启动");
//                            ToastUtils.showShort("服务启动成功");

                            System.out.println("请输入:");
                            out.write(OutputCollection.COMMAND);
                            out.flush();

                            byte[] byteArray = new byte[1024];
                            int arrayLength = input.read(byteArray);
                            byte[] newByteArray = new byte[arrayLength];
                            System.arraycopy(byteArray, 0, newByteArray, 0, arrayLength);
                            LogUtils.e("output 读写");
                            Map<String, String> returnMapSheet = OutputCollection.decode(newByteArray);
                            finalMap.put("sheet", returnMapSheet);
                            callBacks.onDataChanged(finalMap);
                        } else {
                            if(socketClient!=null) {
                                socketClient.close();
                            }
                            socketClient = createSocket();
                            ToastUtils.showShort("服务启动成失败");
                        }
                    }
                } catch (Exception e) {
                    if (e instanceof SocketTimeoutException) {
                        ToastUtils.showShort("服务器连接超时");
                        LogUtils.e("连接超时，正在重连");
//                        ReleaseSocekt();
                    } else if (e instanceof NoRouteToHostException) {
                        LogUtils.e("该地址不存在，请检查");
                        ToastUtils.showShort("该地址不存在，请检查");
//                        ReleaseSocekt();
                    } else if (e instanceof ConnectException) {
                        LogUtils.e("连接异常或被拒绝，请检查");
                        ToastUtils.showShort("连接异常或被拒绝，请检查");
//                        ReleaseSocekt();
                    }
                }
            }
        }.start();

    }

    private Socket createSocket() {
        Socket socketClient = null;
        try {
            if (socketClient != null) {
                socketClient.close();
            }

            if (out != null) {
                out.close();
            }
            if (input != null) {
                input.close();
            }
            socketClient = new Socket(HOST, PORT);
            socketClient.setSoTimeout(TIMEOUT);
            out = new DataOutputStream(socketClient.getOutputStream());
            input = new DataInputStream(socketClient.getInputStream());
        } catch (Exception e) {
        }
        return socketClient;
    }


    private void ReleaseSocekt() {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        if (input != null) {
            try {
                input.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        if (socketClient != null) {
            try {
                socketClient.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            socketClient = null;
        }
        if (isReConnect) {
            init(HOST, PORT);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        init(HOST, PORT);
        return super.onStartCommand(intent, flags, startId);

    }

    public static void start(Context context) {
        if (context == null) {
            throw new NullPointerException("Context can not be null!");
        }
        Intent intent = new Intent(context, PushService.class);
        context.startService(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();


    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class PushBinder extends Binder {
        public PushService getPushService() {
            return PushService.this;
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    /**
     * 重启服务
     */
    public static void restart() {
        stop(MyMultiDexApplication.getContext());
        start(MyMultiDexApplication.getContext());
    }

    public static void stop(Context context) {
        if (context == null) {
            throw new NullPointerException("Context can not be null!");
        }
        Intent intent = new Intent(context, PushService.class);
        context.stopService(intent);
        LogUtils.e("关闭了连接");
    }

    public static interface SocketCallBack {
        //        void onDataChanged(String dataName,String data);
        void onDataChanged(Map<String, Map<String, String>> returnMap);

    }

    private SocketCallBack callBacks;

    public void registerCallBack(SocketCallBack callBack) {
        this.callBacks = callBack;
    }


}
